# -*- coding: utf-8 -*-
'''
Created on 2013-7-25

@author: cl.lam
'''
from flask import request
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_
from flask.helpers import jsonify


from sys2do.views import BasicView
from sys2do.util.common import _g
from sys2do.util.decorator import templated, loginRequired, activetab
from sys2do.constant import TAB_HOME, IVTNT_APPROVE, SYSTEM_DATETIME_FORMAT
from sys2do.model import qry, Item, InventoryNoteDtlItem, InventoryNoteDtl, InventoryNote





__all__ = ['bpTrc']

bpTrc = Blueprint( 'bpTrc', __name__ )

class RptView( BasicView ):

    template_folder = "trc"

    @templated( "index.html" )
    @activetab( TAB_HOME )
    @loginRequired
    def index( self ):
        form = SrhForm( request.form )
        no = _g( 'no' )
        return {'form' : form , 'result' : self._trace( no )}



    def _trace( self, no ):
        if not no : return []
        no = no.strip()
        cs = [ Item.no == no,
               Item.id == InventoryNoteDtlItem.itemID,
               InventoryNoteDtlItem.dtlID == InventoryNoteDtl.id,
               InventoryNoteDtlItem.hdrID == InventoryNote.id,
               InventoryNote.status == IVTNT_APPROVE,
#                InventoryNoteDtl.sIvtLtnID == InventoryLocation.id,
               ]
        return qry( InventoryNote, InventoryNoteDtl ).filter( and_( *cs ) ).order_by( InventoryNote.appTime )



    def ajaxTrc( self ):
        no = _g( 'no' )
        data = []
        for hdr, dtl in self._trace( no ) :

            data.append( {
                         'appTime' : hdr.appTime.strftime( SYSTEM_DATETIME_FORMAT ),
                         'createBy' : unicode( hdr.createBy ),
                         'refer' : hdr.refer,
                         'event' : u'从 [%s] 进入到 [%s] 。' % ( dtl.sIvtLtn, dtl.dIvtLtn )
                         } )
        return jsonify( {'code' : 0 , 'data' : data} )


bpTrc.add_url_rule( '/', view_func = RptView.as_view( 'view' ), defaults = {'action':'index'} )
bpTrc.add_url_rule( '/<action>', view_func = RptView.as_view( 'view' ) )


#===============================================================================
# form class
#===============================================================================

from wtforms import Form, TextField

class SrhForm( Form ):
    no = TextField( u'商品条码编号', )
